<?php

/**
 * Created by PhpStorm.
 * User: GadflyBSD
 * Date: 16/3/14
 * Time: 16:41
 */
class CustomerModel extends PublicModel{

	public function registerUser($param){
		$url = 'http://s.mywoka.com/index.php/Service/Api';
		$data = array(
			'op'		=> 'register',
			'mobile'    => $param['mobile'],
			'password'	=> $param['password'],
		);
		return $this->curlData($url, $data, 'POST');
	}

	public function getUserInfo(){
		$sess = session('waka');
		if(session('?waka') && $sess && is_array($sess['sideInfo'])){
			if(is_null($sess['sideInfo']['bid'])){
				return array('errcode' => '30500' , 'data' => $sess);
			}else{
				foreach(array('idcard_url_1', 'idcard_url_2', 'student_card_url', 'survey_url') AS $val){
					$sess['sideInfo'][$val] = (is_null($sess['sideInfo'][$val]))?'notImg':$sess['sideInfo'][$val];
				}
				$school = $this->getNgOptions('School');
				$survey = M('WakaBindView')->where('role="survey"')->field('nickname, schoolname, survey_id')->select();
				return array('errcode' => '0', 'content' => '汪卡用户已经绑定微信!', 'data' => $sess['sideInfo'], 'school' => $school['data'], 'survey' => $survey);
			}
		}else{
			return array('errcode' => '30500');
		}
	}

	public function getWeixin(){
		return seesion('weixinInfo');
	}

	public function bindWaka($param){
		$realname = M('WakaRealname');
		$bind = M('WakaBind');
		$wx = session('waka');
		$local = $this->validation('UserLocal', array('mobile' => $param['mobile'], 'password' => $param['password']));
		if($local['type'] == 'Error'){
			$remote = $this->validation('StudentRemote', array('mobile' => $param['mobile'], 'password' => $param['password']));
			$halt = randstr();
			$data = array(
				'uid'       => $wx['sideInfo']['uid'],
				'password'  => md5(md5($param['password']).$halt),
				'halt'      => $halt,
				'remark'    => $param['mobile'],
				'recip'     => get_client_ip(),
				'dataline'  => time(),
			);
			if($remote['type'] == 'Success'){
				$target = '/Public/Upload/Customer';
				$post = array();
				/*foreach($remote['data'] AS $key => $val){
					if(in_array($key, array('headimgurl', 'idcard_url_1', 'idcard_url_2', 'yikatong_url', 'student_card_url', 'other_url'))){
						log::write($val, $key);
						if($val && !is_null($val) && !empty($val)){
							$res = $this->getMedia($val, $target);
							if($res['type'] == 'error')
								return json_encode($res);
							else
								$post[$key] = 'http://sta.mywoka.com' . $res['url'];
						}
					}elseif($key != 'id'){
						if($key == 'student_id')
							$post['student_card'] = $val;
						else
							$post[$key] = $val;
					}
				}*/
				$post['telephone'] = $param['mobile'];
				$post['dataline'] = time();
				$rid = $this->curd(array('type'=> 'add', 'model' => $realname, 'data'  => $post));
				if($rid['errcode'] == '0'){
					$data['rid'] = $rid['insID'];
					$state = $this->getCache('userState_bindWaka');
					$data['student_id'] = $remote['data']['uuid'];
					$data['unite'] = $state['id'];
					$recid = $this->curd(array('type'=> 'add', 'model' => $bind, 'data' => $data));
					if($recid['errcode'] == '0'){
						$wx['siteInfo'] = $bind->where('id='.$recid['insID'])->find();
						session('waka', $wx);
						return array('errcode' => '0', 'content' => '微信用户绑定汪卡用户成功!');
					}else{
						return $recid;
					}
				}else{
					return $rid;
				}
			}else{
				$register = $this->register($param);
				if($register['errcode'] == '0'){
					$wx['siteInfo'] = $register['data'];
					session('waka', $wx);
				}
				return $register;
			}
		}else{
			return array('errcode' => '30501');
		}
	}

	public function register($param){
		$url = 'http://admin.mywoka.com/stages/register/saveRegisterhtml.action';
		$register = json_decode($this->curlData($url, array('telephone' => $param['mobile'], 'pwd' => $param['password'], 'name' => 'wx_user_'.randstr(8)), 'POST'));
		if($register['success']){
			$remote = $this->validation('StudentRemote', array('mobile' => $param['mobile'], 'password' => $param['password']));
			$state = $this->getCache('userState_registerWaka');
			$data['unite'] = $state['id'];
			$data['rid'] = M('WakaRealname')->add(array('uuid' => $remote['data']['id']));
			$recid = $this->curd(array('type'=> 'add', 'model' => M('WakaBind'), 'data' => $data));
			if($recid['errcode'] == '0'){
				$data = M('WakaBind')->where('id='.$recid)->find();
				return array('errcode' => '0', 'content' => '微信用户注册汪卡用户成功!', 'data' => $data);
			}else{
				return $recid;
			}
		}else{
			return array('errcode' => '30502');
		}
	}

	public function bindSurvey($param){
		if(M('WakaBindView')->where('survey_name="'.$param['username'].'"')->count() == 0){
			$bind = M('WakaBind');
			$survey = $this->validation('SurveyRemote', $param);
			if($survey['type'] == 'Success'){
				$wx = session('waka');
				$data = array(
					'survey_id'         => $survey['data']['id'],
					'survey_name'       => $param['username'],
					'survey_password'   => md5(md5($param['password']).$wx['sideInfo']['halt']),
					'survey_school'     => $survey['data']['schoolcode'],
					'role'              => 'survey'
				);
				$save = $this->curd(array('type'=> 'save', 'model' => $bind, 'where' => 'bid='.$wx['sideInfo']['bid'], 'data' => $data));
				if($save['errcode'] == '0'){
					return array('errcode' => '0', 'content' => '微信用户绑定尽调员操作成功!');
				}else{
					return $save;
				}
			}else{
				return array('errcode' => '30504');
			}
		}else{
			return array('errcode' => '30503');
		}
	}

	public function setUserInfo($param){
		Vendor('Weixin');
		$weixin = new Weixin('WAKA');
		$target = '/Upload/Customer';
		$waka = session('wakaInfo');
		if($param['idcard1']){
			$res = $weixin->get_media($param['idcard1'], $target);
			if($res['type'] == 'error')
				return $res;
			else
				$param['idcard_url_1'] = $res['url'];
		}
		if($param['idcard2']){
			$res = $weixin->get_media($param['idcard2'], $target);
			if($res['type'] == 'error')
				return $res;
			else
				$param['idcard_url_1'] = $res['url'];
		}
		if($param['xscard']){
			$res = $weixin->get_media($param['xscard'], $target);
			if($res['type'] == 'error')
				return $res;
			else
				$param['student_card_url'] = $res['url'];
		}
		$state = $this->getCache('userState_realname');
		$param['unite'] = $state['id'];
		$state = $this->getCache('userState_editMobile');
		$saveUser = $this->curd(array(
			'model' => M('WangkaUser'),
			'type'  => 'save',
			'where' => 'uid="'.$waka['uid'].'"',
			'data'  => array('mobile' => $param['mobile'], 'status' => $state['id'])
		));
		if($saveUser['errcode'] == '0'){
			$saveBind = $this->curd(array(
				'model' => M('WakaBind'),
				'type'  => 'save',
				'where' => 'bid='.$waka['bid'],
				'data'  => $param
			));
			if($saveBind['errcode'] == '0'){
				return array('errcode' => '0', 'content' => '微信用户实名认证操作成功!',);
			}else{
				return array('errcode' => '30509');
			}
		}else{
			return array('errcode' => '30002');
		}
	}

	public function getShopInfo($param){
		return M('WangkaBindView')->where('md5key="'.$param.'"')->find();
	}

	public function getQrcodeData($param){
		switch(strlen($param)){
			case 32:
				$waka = session('wakaInfo');
				if($waka['role'] == 'survey'){
					$data = M('PayWangkaView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where('id="'.$param.'"')->find();
					return array('type' => 'survey', 'content' => '正确获取数据', 'data' => $data);
				}else{
					return array('type' => 'Error', 'content' => '没有权限, 非法的扫描结果! ');
				}
			case 36:
				if (preg_match("/^[0-9A-Z]{8}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{12}$/", $param)) {
					$data = M('WangkaShop')->where('md5key="'.$param.'"')->find();
					return array('type' => 'Success', 'content' => '正确获取数据', 'data' => $data);
				}else{
					return array('type' => 'Error', 'content' => '非法的扫描结果! ');
				}
			default:
				return array('type' => 'Error', 'content' => '非法的扫描结果! ');
		}
	}

	public function getSurveyList(){
		return $this->curd(array(
			'model' => M('WakaBindView'),
			'where' => 'role = "survey"',
			'type'  => 'select'
		));
	}

	/**
	 * 竟调员尽职调查表单提交控制器
	 * @param $post
	 *
	 * @return array|string
	 */
	public function setSurvey($post){
		$data['survey_dataline'] = time();
		$app_primary = M('WakaRealname')->where('rid='.$post['rid'])->getField('uuid');
		log::write(M('WakaRealname')->getLastSql(), 'uuid');
		switch($post['tp']){
			case 'Pass':
				Vendor('Weixin');
				$weixin = new Weixin('WAKA');
				$target = '/Public/Upload/Customer';
				if($post['survey_1']){
					$res = $weixin->get_media($post['survey_1'], $target);
					if($res['type'] == 'error')
						return $res;
					else
						$data['survey_1'] = $res['url'];
				}
				if($post['survey_2']){
					$res = $weixin->get_media($post['survey_2'], $target);
					if($res['type'] == 'error')
						return $res;
					else
						$data['survey_2'] = $res['url'];
				}
				if($post['survey_other']){
					$res = $weixin->get_media($post['survey_other'], $target);
					if($res['type'] == 'error')
						return $res;
					else
						$data['survey_other'] = $res['url'];
				}
				$data['state'] = 1;
				$remote = array(
					'customer_id'   => $app_primary,
					'hezhao_pic'    => $data['survey_1'],
					'agreement_pic' => $data['survey_2'],
					'other_pic'     => $data['survey_other'],
				);
				$url = 'http://admin.mywoka.com/stages/realnameclient/checkRealNameInfoSubmit.action';
				log::write(json_encode_plus($remote));
				$return = $this->curlData($url, $remote, 'POST');
				break;
			case 'Reject':
				$data = array(
					'cause'             => $post['cause'],
					'state'             => 2
				);
				$remote = array(
					'customer_id'   => $app_primary,
					'realNameTyoe'  => '-1',
				);
				$url = 'http://admin.mywoka.com/stages/realnameclient/checkRealNameInfoCallback.action';
				$return = $this->curlData($url, $remote, 'POST');
				break;
		}
		if ($return['success']){
			return $return;
		}else{
			$save = $this->curd(array('model' => M('WakaRealname'), 'where' => 'rid='.$post['rid'], 'data' => $data));
			log::write(M('WakaRealname')->getLastSql(), 'save');
			if($save['errcode'] == 0){
				return array('errcode' => '0', 'content' => '成功完成用户尽调工作!祝您工作愉快!');
			}else{
				return $save;
			}
		}
	}

	public function validation($type, $post){
		switch($type){
			case 'StudentRemote':
				$where = array('telephone' => $post['mobile'], 'pwd' => md5($post['password']));
				$data = M('RealnameCustomerView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where($where)->find();
				if(!is_null($data))
					return array('type' => 'Success', 'data' => $data);
				else
					return array('type' => 'Error', 'content' => '远端数据库无此用户');
			case 'SurveyRemote':
				$where = array('name' => $post['username'], 'pwd' => md5($post['password']));
				$data = M('user','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where($where)->find();
				if(!is_null($data))
					return array('type' => 'Success', 'data' => $data);
				else
					return array('type' => 'Error', 'content' => '远端数据库无此用户');
			case 'UserLocal':
				$pwd = M('WakaBindView')->where('mobile="'.$post['mobile'].'"')->field('uid, password, halt')->find();
				if(md5(md5($post['password']).$pwd['halt']) == $pwd['password'])
					return array('type' => 'Success', 'data' => M('WakaBindView')->where('uid='.$pwd['uid'])->field('password, halt', true)->find());
				else
					return array('type' => 'Error', 'content' => '本地数据库无此用户');
		}
	}

	public function recharge(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_cust_id'  => I('get.cid'),
			'trans_amt'     => '6666.00',
		);
		return $pnr->recharge($post, '03090000', 'D', 'recharge');
	}

	public function rechargeSuccess($data){}

	public function rechargeFail($data){}

}